import * as React from 'react'
import { Form, Input, Button, Upload, message, Modal } from 'antd';
import './index.scss'

import api from '../../../api'
import getBase64 from '../../../utils/getBase64'
import icon from '../../../config/iconConfig'
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'
import { uploadAction } from '../../../constants'

import { useSelector, useDispatch } from 'react-redux'

const IconFont = icon.icon()


const PostArticle = () => {
    const [previewVisible, setPreviewVisible] = React.useState(false) // 标识是否显示大图预览Modal
    const [previewImage, setPreviewImage] = React.useState('') // 大图的url
    const [fileList, setFileList] = React.useState([])
    /*{
        uid: '-1', // 每个file都有自己唯一的id
        name: 'xxx.png', // 图片文件名
        status: 'done', // 图片状态: done-已上传, uploading: 正在上传中, removed: 已删除
        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', // 图片地址
    },*/
    const fromRef = React.useRef()
    const userState = useSelector(state => state.user);
    const dispatch = useDispatch();

    const layout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 10 },
    };

    const uploadButton = (
        <div>
            <IconFont type="icon-zengjiatianjiajiajian" />
            <div>Upload</div>
        </div>
    );

    /*
    获取所有已上传图片文件名的数组
    */
    // const getImgs  = () => {
    //     return fileList.map(file => file.name)
    // }

    const postData = async (value) => {
        const a_user_id = JSON.parse(userState.data)[0].userid
        const creat_time = new Date().toLocaleString();
        const content = value.content.toHTML()
        value = { ...value, creat_time, images: fileList[0]?fileList[0].url:'', a_user_id, content }
        api.article.addArticle(value).then(res => {
            console.log(res);
            if (res.data.status === 0) {
                message.success("文章发布成功");
            } else {
                message.error(res.data.msg);
            }
        })
    }
    const handleCancel = () => {
        setPreviewVisible(false);
    }

    const handlePreview = async (file) => {
        console.log('handlePreview()', file)
        if (!file.url && !file.preview) {
            file.preview = await getBase64.getBase64(file.originFileObj);
        }
        // 显示指定file对应的大图
        setPreviewVisible(true);
        setPreviewImage(file.url || file.thumbUrl)
    };
    /*
    file: 当前操作的图片文件(上传/删除)
    fileList: 所有已上传图片文件对象的数组
     */
    const handleChange = async ({ file, fileList }) => {
        console.log('handleChange()', file.status, fileList.length, file === fileList[fileList.length - 1])

        // 一旦上传成功, 将当前上传的file的信息修正(name, url)
        if (file.status === 'done') {
            const result = file.response  // {status: 0, data: {name: 'xxx.jpg', url: '图片地址'}}
            if (result.status === 0) {
                message.success('上传图片成功!')
                const { name, url } = result.data
                file = fileList[fileList.length - 1]
                file.name = name
                file.url = url
            } else {
                message.error('上传图片失败')
            }
        } else if (file.status === 'removed') { // 删除图片
            const result = await api.user.reqDeleteImg(file.name)
            console.log(result);
            if (result.data.status === 0) {
                message.success('删除图片成功!')
            } else {
                message.error('删除图片失败!')
            }
        }

        // 在操作(上传/删除)过程中更新fileList状态
        setFileList(fileList)
    };

    const controls = ['bold', 'italic', 'underline', 'text-color', 'separator', 'link', 'separator', 'media']
    return (
        <div className='post-artilce'>
            <Form {...layout} name="artilce-messages" onFinish={postData}>
                <Form.Item name="title" label="title" rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item name="desc" label="desc" rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item name='images' label='images'>
                    <Upload
                        action={uploadAction} /*上传图片的接口地址*/
                        accept='image/*'  /*只接收图片格式*/
                        name="avatar"
                        listType="picture-card"  /*卡片样式*/
                        fileList={fileList}  /*所有已上传图片文件对象的数组*/
                        onPreview={handlePreview}
                        onChange={handleChange}
                    >
                        {fileList.length >= 1 ? null : uploadButton}
                    </Upload>
                </Form.Item>
                <Form.Item name='content' label='content' rules={[{ required: true }]}>
                    <BraftEditor
                        ref={fromRef}
                        controls={controls}
                        placeholder="请输入正文内容"
                    />
                </Form.Item>

                <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>
                    <Button type="primary" htmlType="submit">
                        Submit
                    </Button>
                </Form.Item>
            </Form>
            <Modal
                visible={previewVisible}
                footer={null}
                onCancel={handleCancel}
            >
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
        </div>
    );
}

export default PostArticle